import "./appointment.css"

import { useState, useEffect } from 'react';
import {
    Table, Button, Input, Select, Card, Badge,
    Avatar, Space, Popconfirm, Modal, Typography,
    Statistic, Row, Col, message, DatePicker,
    Skeleton
} from 'antd';
import {
    PlusOutlined, SearchOutlined, CalendarOutlined, 
    EditOutlined, EyeOutlined, DeleteOutlined,
  
} from '@ant-design/icons';
import { AppointmentDetails } from "../../component/appointment/AppointmentDetails";
import { AddAppointment } from "../../component/appointment/AddAppointment";
import UpdateAppointment from "../../component/appointment/updateAppointment";
const { RangePicker } = DatePicker;

// 预约数据
const appointmentData = [
    {
        id: 'A20230615001',
        customer: {
            name: '张晓明',
            phone: '138****5678',
            avatar: 'https://picsum.photos/id/237/40/40'
        },
        service: '推拿按摩',
        doctor: '李员工',
        date: '2023-06-15',
        time: '09:30 - 10:30',
        price: '188.00',
        status: 'completed'
    },
    {
        id: 'A20230615002',
        customer: {
            name: '王丽',
            phone: '139****8765',
            avatar: 'https://picsum.photos/id/64/40/40'
        },
        service: '针灸治疗',
        doctor: '陈员工',
        date: '2023-06-15',
        time: '11:00 - 12:00',
        price: '268.00',
        status: 'ongoing'
    },
    {
        id: 'A20230615003',
        customer: {
            name: '刘建国',
            phone: '136****2345',
            avatar: 'https://picsum.photos/id/91/40/40'
        },
        service: '艾灸养生',
        doctor: '赵员工',
        date: '2023-06-15',
        time: '14:00 - 15:00',
        price: '228.00',
        status: 'confirmed'
    },
    {
        id: 'A20230615004',
        customer: {
            name: '陈明',
            phone: '135****6789',
            avatar: 'https://picsum.photos/id/26/40/40'
        },
        service: '拔罐疗法',
        doctor: '李员工',
        date: '2023-06-15',
        time: '16:30 - 17:30',
        price: '168.00',
        status: 'booked'
    },
    {
        id: 'A20230614028',
        customer: {
            name: '林小红',
            phone: '137****3456',
            avatar: 'https://picsum.photos/id/65/40/40'
        },
        service: '中药熏蒸',
        doctor: '王员工',
        date: '2023-06-14',
        time: '15:00 - 16:30',
        price: '298.00',
        status: 'cancelled'
    }
];

// 统计数据
const statisticsData = {
    today: { count: 24, completedRate: 75 },
    week: { count: 156, completedRate: 60 },
    month: { count: 589, completedRate: 45 },
    cancelled: { count: 18, percentage: 12 }
};

// 服务项目列表
const serviceOptions = [
    { value: '', label: '全部项目' },
    { value: 'tuina', label: '推拿按摩' },
    { value: 'zhenjiu', label: '针灸治疗' },
    { value: 'aijiu', label: '艾灸养生' },
    { value: 'baguan', label: '拔罐疗法' },
    { value: 'zhongyao', label: '中药熏蒸' }
];



// 状态标签样式映射
const statusTagMap = {
    booked: <Badge status="default" text="已预约" />,
    confirmed: <Badge status="processing" text="待确认" />,
    ongoing: <Badge status="processing" text="进行中" />,
    completed: <Badge status="success" text="已完成" />,
    cancelled: <Badge status="error" text="已取消" />
};

const Appointment = () => {
    // 状态管理
    const [searchText, setSearchText] = useState('');
    const [dateRange, setDateRange] = useState(null);
    const [selectedService, setSelectedService] = useState('');
    const [selectedStatus, setSelectedStatus] = useState('');
    const [selectedDoctor, setSelectedDoctor] = useState('');
    const [currentPage, setCurrentPage] = useState(1);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [selectedAppointment, setSelectedAppointment] = useState(null);
    const [filteredData, setFilteredData] = useState(appointmentData);
    //新增预约
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [isUpdateModalVisible,setIsUpdateModalVisible]=useState(false);
    const [isShow, set_isShow] = useState(true);
   
    setTimeout(() => {
        set_isShow(false);
    }, 1000);
    // 筛选数据
    useEffect(() => {
        let result = [...appointmentData];

        // 搜索筛选
        if (searchText) {
            const text = searchText.toLowerCase();
            result = result.filter(item =>
                item.customer.name.toLowerCase().includes(text) ||
                item.customer.phone.includes(text)
            );
        }

        // 服务项目筛选
        if (selectedService) {
            const serviceMap = {
                tuina: '推拿按摩',
                zhenjiu: '针灸治疗',
                aijiu: '艾灸养生',
                baguan: '拔罐疗法',
                zhongyao: '中药熏蒸'
            };
            result = result.filter(item => item.service === serviceMap[selectedService]);
        }

        // 状态筛选
        if (selectedStatus) {
            result = result.filter(item => item.status === selectedStatus);
        }

        // 员工筛选
        if (selectedDoctor) {
            const doctorMap = {
                li: '李员工',
                chen: '陈员工',
                zhao: '赵员工',
                wang: '王员工'
            };
            result = result.filter(item => item.doctor === doctorMap[selectedDoctor]);
        }



        setFilteredData(result);
        setCurrentPage(1); // 重置到第一页
    }, [searchText, dateRange, selectedService, selectedStatus, selectedDoctor]);

    // 查看详情
    const handleViewDetail = (record) => {

        setSelectedAppointment(record);
        setIsModalVisible(true);
    };

    // 编辑预约
    const handleEdit = (record) => {
        setSelectedAppointment(record);
        setIsUpdateModalVisible(true);
       
    };

    // 取消预约
    const handleCancel = (record) => {
        if (record.status !== 'cancelled') {
            // 这里会有实际的取消逻辑
            message.success(`已取消预约: ${record.id}`);
        } else {
            message.warning('该预约已取消');
        }
    };





    // 表格列定义
    const columns = [
        {
            title: '预约编号',
            dataIndex: 'id',
            key: 'id',
            width: 120,
        },
        {
            title: '客户信息',
            key: 'customer',
            render: (_, record) => (
                <Space align="center">
                    <Avatar src={record.customer.avatar} alt={record.customer.name} />
                    <div>
                        <div>{record.customer.name}</div>
                        <div style={{ fontSize: 12, color: '#888' }}>{record.customer.phone}</div>
                    </div>
                </Space>
            ),
        },
        {
            title: '理疗项目',
            dataIndex: 'service',
            key: 'service',
        },
      
        {
            title: '预约时间',
            key: 'time',
            render: (_, record) => (
                <div>
                    <div>{record.date}</div>
                    <div style={{ fontSize: 12, color: '#888' }}>{record.time}</div>
                </div>
            ),
        },
        {
            title: '费用',
            key: 'price',
            render: (_, record) => `¥${record.price}`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => statusTagMap[status],
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="small">
                    <Button
                        icon={<EyeOutlined />}
                        size="small"
                        onClick={() => handleViewDetail(record)}
                        type="primary"
                    >
                        详情
                    </Button>

                    {record.status !== 'completed' && record.status !== 'cancelled' && (
                        <Button
                            icon={<EditOutlined />}
                            size="small"
                            onClick={() => handleEdit(record)}
                            type="default"
                        >
                            编辑
                        </Button>
                    )}



                    {record.status !== 'completed' && record.status !== 'cancelled' && (
                        <Popconfirm
                            title="确定要取消此预约吗？"
                            onConfirm={() => handleCancel(record)}
                            okText="是"
                            cancelText="否"
                        >
                            <Button
                                icon={<DeleteOutlined />}
                                size="small"
                              
                                danger
                            >
                                取消
                            </Button>
                        </Popconfirm>
                    )}

                 
                </Space>
            ),
        },
    ];

    // 分页配置
    const paginationConfig = {
        current: currentPage,
        pageSize: 5,
        total: filteredData.length,
        onChange: (page) => setCurrentPage(page),
        showSizeChanger: false,
        showTotal: (total) => `共 ${total} 条记录`,
    };

    return (
        <div>
            {isShow ? (
                <Skeleton paragraph={{ rows: 10 }} active></Skeleton>
            ) : (
                <div>{/* 页面标题和操作区 */}
                    <div style={{ marginBottom: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div>
                            <Typography.Title level={2} style={{ marginBottom: 5 }}>预约管理</Typography.Title>
                            <Typography.Text type="secondary">查看和管理所有客户预约记录</Typography.Text>
                        </div>
                        <div>
                            <Button type="primary" onClick={()=>setIsAddModalVisible(true)}>新增预约</Button>
                        </div>
                      
                    </div>

                    {/* 筛选和搜索区 */}
                    <Card style={{ marginBottom: 20 }}>
                        <Row gutter={[16, 16]}>
                            <Col xs={24} sm={12} md={6}>
                                <RangePicker
                                    placeholder={['开始日期', '结束日期']}
                                    value={dateRange}
                                    onChange={setDateRange}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                            <Col xs={24} sm={12} md={6}>
                                <Select
                                    placeholder="选择理疗项目"
                                    style={{ width: '100%' }}
                                    options={serviceOptions}
                                    value={selectedService}
                                    onChange={setSelectedService}
                                />
                            </Col>
                            <Col xs={24} sm={12} md={6}>
                               <Input
                                    placeholder="搜索客户姓名或电话..."
                                    prefix={<SearchOutlined />}
                                    value={searchText}
                                    onChange={(e) => setSearchText(e.target.value)}
                                />
                            </Col>
                            <Col xs={24} sm={12} md={6}>
                                 <Button
                                    type="primary"
                                    style={{ flex: 1 }}
                                >
                                    应用筛选
                                </Button>
                            </Col>
                        </Row>

                    
                    </Card>

                    {/* 预约统计 */}
                    <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
                        <Col xs={24} sm={12} lg={6}>
                            <Card>
                                <Row gutter={16} align="middle">
                                    <Col span={16}>
                                        <Typography.Text type="secondary">今日预约总数</Typography.Text>
                                        <Statistic title={statisticsData.today.count} valueStyle={{ fontSize: 24 }} />
                                    </Col>
                                    <Col span={8} style={{ textAlign: 'center' }}>
                                        <div style={{
                                            backgroundColor: '#8B5A2B1A',
                                            width: 48,
                                            height: 48,
                                            borderRadius: 8,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            margin: '0 auto'
                                        }}>
                                            <CalendarOutlined style={{ color: '#8B5A2B', fontSize: 20 }} />
                                        </div>
                                    </Col>
                                </Row>
                                <div style={{ marginTop: 12 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', fontSize: 12 }}>
                                        <div style={{
                                            height: 4,
                                            flex: 1,
                                            backgroundColor: '#e8e8e8',
                                            borderRadius: 2,
                                            overflow: 'hidden'
                                        }}>
                                            <div
                                                style={{
                                                    height: '100%',
                                                    width: `${statisticsData.today.completedRate}%`,
                                                    backgroundColor: '#8B5A2B'
                                                }}
                                            ></div>
                                        </div>
                                        <span style={{ marginLeft: 8, color: '#888' }}>
                                            {statisticsData.today.completedRate}% 已完成
                                        </span>
                                    </div>
                                </div>
                            </Card>
                        </Col>

                        <Col xs={24} sm={12} lg={6}>
                            <Card>
                                <Row gutter={16} align="middle">
                                    <Col span={16}>
                                        <Typography.Text type="secondary">本周预约总数</Typography.Text>
                                        <Statistic title={statisticsData.week.count} valueStyle={{ fontSize: 24 }} />
                                    </Col>
                                    <Col span={8} style={{ textAlign: 'center' }}>
                                        <div style={{
                                            backgroundColor: '#2F4F4F1A',
                                            width: 48,
                                            height: 48,
                                            borderRadius: 8,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            margin: '0 auto'
                                        }}>
                                            <PlusOutlined style={{ color: '#2F4F4F', fontSize: 20 }} />
                                        </div>
                                    </Col>
                                </Row>
                                <div style={{ marginTop: 12 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', fontSize: 12 }}>
                                        <div style={{
                                            height: 4,
                                            flex: 1,
                                            backgroundColor: '#e8e8e8',
                                            borderRadius: 2,
                                            overflow: 'hidden'
                                        }}>
                                            <div
                                                style={{
                                                    height: '100%',
                                                    width: `${statisticsData.week.completedRate}%`,
                                                    backgroundColor: '#2F4F4F'
                                                }}
                                            ></div>
                                        </div>
                                        <span style={{ marginLeft: 8, color: '#888' }}>
                                            {statisticsData.week.completedRate}% 已完成
                                        </span>
                                    </div>
                                </div>
                            </Card>
                        </Col>

                        <Col xs={24} sm={12} lg={6}>
                            <Card>
                                <Row gutter={16} align="middle">
                                    <Col span={16}>
                                        <Typography.Text type="secondary">本月预约总数</Typography.Text>
                                        <Statistic title={statisticsData.month.count} valueStyle={{ fontSize: 24 }} />
                                    </Col>
                                    <Col span={8} style={{ textAlign: 'center' }}>
                                        <div style={{
                                            backgroundColor: '#52c41a1a',
                                            width: 48,
                                            height: 48,
                                            borderRadius: 8,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            margin: '0 auto'
                                        }}>
                                            <PlusOutlined style={{ color: '#52c41a', fontSize: 20 }} />
                                        </div>
                                    </Col>
                                </Row>
                                <div style={{ marginTop: 12 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', fontSize: 12 }}>
                                        <div style={{
                                            height: 4,
                                            flex: 1,
                                            backgroundColor: '#e8e8e8',
                                            borderRadius: 2,
                                            overflow: 'hidden'
                                        }}>
                                            <div
                                                style={{
                                                    height: '100%',
                                                    width: `${statisticsData.month.completedRate}%`,
                                                    backgroundColor: '#52c41a'
                                                }}
                                            ></div>
                                        </div>
                                        <span style={{ marginLeft: 8, color: '#888' }}>
                                            {statisticsData.month.completedRate}% 已完成
                                        </span>
                                    </div>
                                </div>
                            </Card>
                        </Col>

                        <Col xs={24} sm={12} lg={6}>
                            <Card>
                                <Row gutter={16} align="middle">
                                    <Col span={16}>
                                        <Typography.Text type="secondary">取消预约数</Typography.Text>
                                        <Statistic title={statisticsData.cancelled.count} valueStyle={{ fontSize: 24 }} />
                                    </Col>
                                    <Col span={8} style={{ textAlign: 'center' }}>
                                        <div style={{
                                            backgroundColor: '#CD5C5C1A',
                                            width: 48,
                                            height: 48,
                                            borderRadius: 8,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            margin: '0 auto'
                                        }}>
                                            <PlusOutlined style={{ color: '#CD5C5C', fontSize: 20 }} />
                                        </div>
                                    </Col>
                                </Row>
                                <div style={{ marginTop: 12 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', fontSize: 12 }}>
                                        <div style={{
                                            height: 4,
                                            flex: 1,
                                            backgroundColor: '#e8e8e8',
                                            borderRadius: 2,
                                            overflow: 'hidden'
                                        }}>
                                            <div
                                                style={{
                                                    height: '100%',
                                                    width: `${statisticsData.cancelled.percentage}%`,
                                                    backgroundColor: '#CD5C5C'
                                                }}
                                            ></div>
                                        </div>
                                        <span style={{ marginLeft: 8, color: '#888' }}>
                                            占总预约 {statisticsData.cancelled.percentage}%
                                        </span>
                                    </div>
                                </div>
                            </Card>
                        </Col>
                    </Row>

                    {/* 预约列表 */}
                    <Card>
                        <Table
                            bordered
                            columns={columns}
                            dataSource={filteredData}
                            rowKey="id"
                            pagination={paginationConfig}
                            scroll={{ x: 'max-content' }}
                        />
                    </Card>
                    {/* 新增预约模态框 */}
                    <Modal
                        title="管理员新增预约（辅助功能）"
                        open={isAddModalVisible}
                        onCancel={() => setIsAddModalVisible(false)}
                        width={600}
                        footer={null}
                    >
                        <AddAppointment />
                    </Modal>
                    {/* 预约详情模态框 */}
                    <Modal
                        title="预约详情"
                        open={isModalVisible}
                        onCancel={() => setIsModalVisible(false)}
                        footer={[
                            <Button key="close" onClick={() => setIsModalVisible(false)}>
                                关闭
                            </Button>
                        ]}

                    >

                        {selectedAppointment && (
                            <AppointmentDetails data={selectedAppointment}></AppointmentDetails>
                        )}

                    </Modal>
                    
                      {/* 预约编辑模态框 */}
                    <Modal
                        title="预约编辑"
                        open={isUpdateModalVisible}
                        onCancel={() => setIsUpdateModalVisible(false)}
                        style={{top:"50px"}}
                           width={800}
                        footer={[
                           
                        ]}

                    >

                        {selectedAppointment && (
                            <UpdateAppointment data={selectedAppointment}></UpdateAppointment>
                        )}

                    </Modal>
                    
                    
                    </div>
            )}


        </div>
    );
};

export default Appointment;
